package com.tsing.common.utils;

import java.security.MessageDigest;

public class MD5Util {

    private static String getMD5Str(String str) {
        String result = null;
        try {
            byte[] bytes = MessageDigest.getInstance("MD5").digest(str.getBytes());
            StringBuffer sb = new StringBuffer();
            for (byte b : bytes) {
                sb.append(byte2HexStr(b));
            }
            result = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 字节标准移位转十六进制方法
     */
    private static String byte2HexStr(byte b) {
        String hexStr = null;
        int n = b;
        if (n < 0) {
            //若需要自定义加密,请修改这个移位算法即可
            n = b & 0x7F + 128;
        }
        hexStr = Integer.toHexString(n / 16) + Integer.toHexString(n % 16);
        return hexStr.toUpperCase();
    }

    public static String getMD5ByStr(String str, int times) {
        String md5 = getMD5Str(str);
        for (int i = 0; i < times; i++) {
            md5 = getMD5Str(md5);
        }
        return md5;
    }

    public static boolean verifyPassword(String str, String MD5Str, int times) {
        return getMD5ByStr(str, times).equals(MD5Str);
    }

}
